<template>
  <div class="file-list">
    <el-card>
      <template #header>
        <div class="header">
          <span>资料管理</span>
          <el-button type="primary" v-if="userType == 9" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            添加资料
          </el-button>
        </div>
      </template>
      
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="文件名">
          <el-input v-model="searchForm.filename" placeholder="请输入文件名"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
      
      <el-table :data="files" style="width: 100%">
        <el-table-column prop="id" label="文件ID" width="80" />
        <el-table-column prop="display_name" label="显示名称" />
        <el-table-column prop="filename" label="原始文件名" />
        <el-table-column prop="saved_filename" label="存储文件名" />
        <el-table-column prop="description" label="文件描述" />
        <el-table-column prop="file_size" label="文件大小" width="100">
          <template #default="scope">
            {{ formatFileSize(scope.row.file_size) }}
          </template>
        </el-table-column>
        <el-table-column prop="file_type" label="文件类型" width="120" />
        <el-table-column prop="watch_num" label="观看次数" width="120" />
        <el-table-column prop="uploader.name" label="上传者" width="100" />
        <el-table-column prop="created_at" label="上传时间" width="180">
          <template #default="scope">
            {{ formatDateTime(scope.row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="scope">
            <el-button type="primary" v-if="userType == 9" text @click="handleEdit(scope.row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 共用对话框：用于新增和编辑 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加资料' : '编辑资料'"
      width="500px"
    >
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px">
        <el-form-item v-if="dialogType === 'add'" label="选择文件" prop="file">
          <el-upload
            v-model:file-list="fileList"
            class="upload-demo"
            :auto-upload="false"
            :limit="1"
            accept="*"
            :on-change="handleFileChange"
          >
            <el-button type="primary">点击选择文件</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="显示名称" prop="display_name">
          <el-input v-model="formData.display_name" placeholder="请输入显示名称"/>
        </el-form-item>
        <el-form-item label="文件描述" prop="description">
          <el-input v-model="formData.description" placeholder="请输入文件描述" type="textarea"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
  <div>
    <!-- 整个页面的加载状态 -->
    <div v-loading="loading" class="loading-container" element-loading-text="文件上传中...">
    </div>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { useUserStore } from '../../store/user'
import api from '../../api'

export default {
  name: 'FileList',
  components: {
    Plus
  },
  setup() {
    const files = ref([])
    const total = ref(0)
    const currentPage = ref(1)
    const pageSize = ref(10)
    const loading = ref(false)
    const userStore = useUserStore()
    
    // 搜索表单
    const searchForm = reactive({
      filename: ''
    })
    
    // 对话框状态
    const dialogVisible = ref(false)
    const userType = ref(0)
    const dialogType = ref('add')
    const formRef = ref(null)
    const fileList = ref([])
    
    // 表单数据
    const formData = reactive({
      id: '',
      display_name: '',
      description: '',
    })
    
    // 表单验证规则
    const formRules = {
      display_name: [
        { required: true, message: '请输入显示名称', trigger: 'blur' }
      ]
    }
    
    // 格式化文件大小
    const formatFileSize = (bytes) => {
      if (bytes === 0) return '0 Bytes'
      const k = 1024
      const sizes = ['Bytes', 'KB', 'MB', 'GB']
      const i = Math.floor(Math.log(bytes) / Math.log(k))
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
    }
    
    // 格式化日期时间
    const formatDateTime = (dateTime) => {
      if (!dateTime) return ''
      const date = new Date(dateTime)
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      })
    }
    
    // 加载文件列表
    const loadFiles = async () => {
      loading.value = true
      userType.value = userStore.user?.category
      try {
        const params = {
          skip: (currentPage.value - 1) * pageSize.value,
          limit: pageSize.value
        }
        
        // 添加搜索条件
        if (searchForm.filename) {
          params.filename = searchForm.filename
        }
        
        const response = await api.get('/chance/files', {
          params: {
            skip: (currentPage.value - 1) * pageSize.value,
            limit: pageSize.value,
            ...searchForm
          }
        })
        files.value = response
        // 假设后端返回了总数，如果没有，这里可能需要额外的API调用来获取总数
        if (searchForm.filename || searchForm.display_name) {
          // 在实际项目中，这里应该调用一个获取过滤后总数的API
          total.value = Math.min(response.length + (currentPage.value - 1) * pageSize.value, 1000)
        } else {
          // 如果没有搜索条件，可以使用简单的处理
          total.value = response.length + (currentPage.value - 1) * pageSize.value
        }
      } catch (error) {
        ElMessage.error('获取文件列表失败')
      } finally {
        loading.value = false
      }
    }
    
    // 查询
    const handleSearch = () => {
      currentPage.value = 1
      loadFiles()
    }
    
    // 重置搜索
    const resetSearch = () => {
      Object.keys(searchForm).forEach(key => {
        searchForm[key] = ''
      })
      currentPage.value = 1
      loadFiles()
    }
    
    // 添加资料
    const handleAdd = () => {
      dialogType.value = 'add'
      // 重置表单
      if (formRef.value) {
        formRef.value.resetFields()
      }
      // 初始化表单数据
      formData.id = ''
      formData.display_name = ''
      formData.description = ''
      fileList.value = []
      dialogVisible.value = true
    }
    
    // 编辑文件
    const handleEdit = (row) => {
      dialogType.value = 'edit'
      // 填充表单数据
      formData.id = row.id
      formData.display_name = row.display_name
      formData.description = row.description || ''
      fileList.value = []
      dialogVisible.value = true
    }
    
    // 处理文件选择变化
    const handleFileChange = (file) => {
      // 自动填充显示名称
      if (!formData.display_name && file.name) {
        formData.display_name = file.name
      }
    }
    
    // 取消操作
    const handleCancel = () => {
      dialogVisible.value = false
      // 清理表单数据
      if (formRef.value) {
        formRef.value.resetFields()
      }
      fileList.value = []
    }
    
    // 提交表单
    const handleSubmit = async () => {
      loading.value = true
      await formRef.value.validate(async (valid) => {
        if (valid) {
          try {
            if (dialogType.value === 'add') {
              // 添加模式：上传文件
              if (fileList.value.length === 0) {
                ElMessage.error('请选择要上传的文件')
                return
              }
              
              const uploadFormData = new FormData()
              uploadFormData.append('file', fileList.value[0].raw)
              uploadFormData.append('display_name', formData.display_name)
              uploadFormData.append('description', formData.description)
              
              await api.post('/chance/files/', uploadFormData)
              loading.value = false
              ElMessage.success('文件上传成功')
            } else {
              // 编辑模式：更新文件信息
              await api.put(`/chance/files/${formData.id}`, formData)
              loading.value = false
              ElMessage.success('编辑文件成功')
            }
            
            handleCancel()
            loadFiles()
          } catch (error) {
            loading.value = false
            ElMessage.error(dialogType.value === 'add' ? '文件上传失败' : '编辑文件失败')
          }
        }
      })
    }
    
    
    
    // 分页处理
    const handleSizeChange = (size) => {
      pageSize.value = size
      loadFiles()
    }
    
    const handleCurrentChange = (current) => {
      currentPage.value = current
      loadFiles()
    }
    
    // 初始加载
    onMounted(() => {
      loadFiles()
    })
    
    return {
      files,
      total,
      currentPage,
      pageSize,
      loading,
      searchForm,
      dialogVisible,
      userType,
      dialogType,
      formRef,
      fileList,
      formData,
      formRules,
      formatFileSize,
      formatDateTime,
      handleSearch,
      resetSearch,
      handleAdd,
      handleEdit,
      handleFileChange,
      handleCancel,
      handleSubmit,
      handleSizeChange,
      handleCurrentChange
    }
  }
}
</script>

<style scoped>
.file-list {
  padding: 0;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.upload-demo {
  display: inline-block;
}

.loading-container {
  padding: 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  background-color: #f9fafb;
  min-height: 200px;
}
</style>